package com.omall.open.sdk.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.crypto.digest.MD5;
import org.apache.dubbo.common.utils.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * 算法计算
 */
public final class SecurityUtil {
	
	public static String getSecurityStr(Map<String,String>  paramMap, String appSecret) {
		String resultStr = null;
        try {
        	String paramStr = "";
        	//平台要求排序
        	Map<String,String>  paramTreeMap = new TreeMap<>();
        	for (Entry<String,String> entry : paramMap.entrySet()) {
        		paramTreeMap.put(entry.getKey(), entry.getValue());
			}
        	for (Entry<String,String> entry : paramTreeMap.entrySet()) {
        		if (StringUtils.isNotEmpty(paramStr)) {
        			paramStr = paramStr + "&" + entry.getKey() + "=" + entry.getValue();
				} else {
					paramStr = paramStr + entry.getKey() + "=" + entry.getValue();
				}
			}
        	String encodeParamStr = Base64.encode(paramStr, StandardCharsets.UTF_8);
        	byte[] digest = new HMac(HmacAlgorithm.HmacSHA256, appSecret.getBytes()).digest(encodeParamStr);
        	resultStr =  MD5.create().digestHex(digest).toLowerCase();
		} catch (Exception e) {
			throw new IllegalStateException("加密失败.");
		}
		return resultStr;
	}
	
	public static void main(String args[]) {
		Map<String,String>  paramMap = new HashMap<>();
		paramMap.put("isv_app_key", "3400eb5f2d6640548978e762ede1e372");
		paramMap.put("access_token", "5ab56f3068146230a93cb1e6a09fe557");
		paramMap.put("need_express", "1");
		paramMap.put("express_code", "ZJS");
		paramMap.put("express_no", "A000989106381");

		paramMap.put("order_sn", "20010310190323621550895107");
		paramMap.put("order_detail_list", "96080608");
		String  str = getSecurityStr(paramMap, "a1cde9b0f04a488cac3644eefe096e0a");
		System.out.println(str);
	}
	
	/**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    public  static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
	

    public static String getMD5Str(String str) {
        MessageDigest messageDigest;

        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            if (!StringUtils.isEmpty(str)) {
                messageDigest.update(str.getBytes("UTF-8"));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("System doesn't support your  EncodingException.");
        }

        byte[] byteArray = messageDigest.digest();

        StringBuilder md5StrBuff = new StringBuilder();

        for (byte aByteArray : byteArray) {
            if (Integer.toHexString(0xFF & aByteArray).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & aByteArray));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & aByteArray));
            }
        }
        return md5StrBuff.toString().toLowerCase();
    }
    
}
